from django.shortcuts import render

from rest_framework.views import APIView,Response
from rest_framework.viewsets import ModelViewSet
from users.models import UserModel,Address
from utils.jwt_token import generate_token
from users.serializer import AddrSer,UserSer
from django.db.models import Q
from utils.force_login import check_login

from shops.models import Shops,Kind,Dishes
from shops.serializer import KindModelSer

class Register(APIView):
    def post(self,request):
        nickname = request.data.get('nickname')
        account = request.data.get('account')
        password = request.data.get('password')
        mobile = request.data.get('mobile')

        if not all([nickname,account,password,mobile]):
            return Response({'code':204,'msg':'用户信息不完整'})
        user = UserModel.objects.filter(Q(account=account) |Q(mobile=mobile))
        print('注册查找的用户信息',user,type(user))
        if user:
            return Response({'code':204,'msg':'账户或者手机号已被注册'})
        else:
            UserModel.objects.create(nickname=nickname,account=account,password=password,mobile=mobile)
            return Response({'code':200,'msg':'注册成功'})



from django.contrib.auth.hashers import check_password
class Login(APIView):
    def post(self,request):
        print('aaaa',request.method,request.path)
        account = request.data.get('account')
        password = request.data.get('password')
        print('登录接受的用户信息',account,password,type(password))

        user = UserModel.objects.get(account=account)
        if not user:
            return Response({'code':204,'msg':'用户不存在'})
        user = UserModel.objects.get(account=account,password=password)
        print('>>>>>>',user.id)
        if user:
            token=generate_token(user)
            return Response({'code':200,'msg':'登录成功','token':token,'id':user.id})
        return Response({'code':204,'msg':'密码错误'})




class UserAPIView(APIView):
    @check_login    #获取用户信息
    def get(self,request):
        user=request.user
        # addr_queryset = Address.objects.filter(user_id=user)    #正向查询
        addr_queryset=user.address_set.all()       #反向查询
        addr_queryset_ser=AddrSer(addr_queryset,many=True)
        data={
            "code":200,
            "msg":"获取用户信息成功",
            "userInfo":{
                    "username":user.nickname,
                    "phone":user.mobile,
                    "addrs":addr_queryset_ser.data,
                        }
        }
        return Response(data)


    @check_login    #修改，更新用户信息，收货地址
    def put(self, request):
        id = request.user.id
        phone = request.data.get('phone')
        addrs = request.data.get("addrs")
        print('收货人信息',addrs)
        try:
            UserModel.objects.filter(id=id).update(mobile=phone)
            for i in addrs:
                print('>>>>',i['id'])
                Address.objects.filter(id=i['id']).update(recipients_addr=i['recipients'],recipients_mobile=i['recipients_mobile'],recipients=i['recipients'])
            return Response({'code': 200, 'msg': '修改用户信息成功'})
        except Exception as e:
            print('修改用户信息失败', e)
            return Response({'code': 204, 'msg': '修改用户信息失败'})




class AddrAPIView(APIView):

    #添加收货地址
    @check_login
    def post(self,request):
        user=request.user
        receiver = request.data.get("receiver")
        receive_mobile = request.data.get("receive_mobile")
        receive_addr = request.data.get("receive_addr")
        is_default = request.data.get("is_default")

        if not all([receiver,receive_mobile,receive_addr]):
            return Response({"code": 204, "msg": "信息不完整"})

        if is_default:      #是 True  就需要把该用户 其它收货地址 修改成取消默认 False
            Address.objects.filter(user=user).update(is_default=False)

        # 3.创建地址对象，存储地址数据
        if Address.objects.filter(recipients=receiver, recipients_mobile=receive_mobile,
                recipients_addr=receive_addr, user=user):
            return Response({"code":204,"msg":"重复添加"})
        else:
            addr=Address.objects.create(recipients=receiver,recipients_mobile=receive_mobile,
                    recipients_addr=receive_addr,is_default=is_default,user=user)

            addr_ser=AddrSer(addr)
            data={
                "code":200,
                "msg":"添加地址成功",
                "addr":addr_ser.data
            }
            return Response(data)

    #删除收货地址
    def delete(self,request):
        addr_id=request.data.get("addr_id")
        # 查询当前地址，并删除
        Address.objects.get(id=addr_id).delete()

        return Response({"code":200,"msg":"删除地址成功"})



    # 加载用户收货地址
    @check_login
    def get(self,request):
        user=request.user
        print('用户对象',user)

        # 反向查询该用户的所有收货地址
        addr_queryset=user.address_set
        addr_queryset_ser=AddrSer(addr_queryset,many=True)

        data={
            "code":200,
            "msg":"获取收货地址成功",
            "addrList":addr_queryset_ser.data
        }
        return Response(data)




class KindView(APIView):
    #获取所有菜品种类
    @check_login
    def get(self,request,pk):
        try:
            shops = Shops.objects.get(id=pk)
            print('这是获取的商家',shops)
        except Exception as e:
            print('获取商家失败', e)
            return Response({'code': 204, 'msg': '这个商家不存在'})

        try:
            shops_kind_set = Kind.objects.filter(shops_id=shops.id)
            kind_all = KindModelSer(shops_kind_set, many=True)
            return Response({'code': 200, 'msg': '获取商家所有菜品种类成功', 'kind_all': kind_all.data})
        except Exception as e:
            print('失败', e)
            return Response({'code': 204, 'msg': '获取商家所有菜品种类失败'})


class Dishes_all(APIView):
    #获取商家所有菜品
    @check_login
    def get(self,request,pk):
        try:
            shops = Shops.objects.get(id=pk)
            print('这是获取的商家',shops)
        except Exception as e:
            print('获取登录商家失败', e)
            return Response({'code': 204, 'msg':'该商家不存在'})
        try:
            dishes_set = Dishes.objects.filter(shops_id=shops.id)
            print('商家所有菜品', dishes_set)
            data = []
            for i in dishes_set:
                print('>>>>>>',i.kind_id)
                kind = Kind.objects.get(id=i.kind_id)
                data_={
                    'id':i.id,
                    'kind_id':kind.id,
                    'kind_name':kind.kind_name,
                    'dishes_name':i.dishes_name,
                    'dishes_price':i.dishes_price,
                    'dishes_picture':i.dishes_picture,
                }
                data.append(data_)
            return Response({'code': 200, 'msg': '获取商家菜品所有菜品成功', 'dishes_all':data})
        except Exception as e:
            print('获取商家菜品所有菜品失败', e)
            return Response({'code': 204, 'msg': '获取商家菜品所有菜品失败'})


class DishesView(APIView):
    # 菜品信息管理
    @check_login
    def post(self,request,pk):
        id = request.data.get('kind_id')
        try:
            shops = Shops.objects.get(id=pk)
            print('这是获取的商家',shops)
        except Exception as e:
            return Response({'code': 204, 'msg':'该商家不存在'})
        try:
            if pk==7:
                dishes_set = Dishes.objects.filter(shops_id=shops.id)
                data = []
                for i in dishes_set:
                    print('>>>>>>', i.kind_id)
                    kind = Kind.objects.get(id=i.kind_id)
                    data_ = {
                        'id':i.id,
                        'kind_id': kind.id,
                        'kind_name': kind.kind_name,
                        'dishes_name': i.dishes_name,
                        'dishes_price': i.dishes_price,
                        'dishes_picture': i.dishes_picture,
                    }
                    data.append(data_)
                return Response({'code': 200, 'msg': '获取商家菜品所有菜品成功', 'kind_dishes': data})
            else:
                kind_dishes_set = Dishes.objects.filter(Q(shops_id=pk) & Q(kind_id=id))
                data = []
                for i in kind_dishes_set:
                    print('>>>>>>', i.kind_id)
                    kind = Kind.objects.get(id=i.kind_id)
                    data_ = {
                        'id':i.id,
                        'kind_id': kind.id,
                        'kind_name': kind.kind_name,
                        'dishes_name': i.dishes_name,
                        'dishes_price': i.dishes_price,
                        'dishes_picture': i.dishes_picture,
                    }
                    data.append(data_)
                return Response({'code': 200, 'msg': '获取商家一个种类所有菜品成功', 'kind_dishes':data})
        except Exception as e:
            return Response({'code': 204, 'msg': '获取商家种类菜品所有菜品失败'})